package edu.geektime.jiangfan.chapter02.bio;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer02 {
    private final static int PORT = 8002;
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(PORT);
        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(() -> {
                try {
                    service(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } ).start();
        }
    }

    private static void service (Socket socket) throws IOException {
        String body = "哦嗨哟 Request Thread BIO";
        // 开启自动刷新
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
        // 输入Http响应头
        printWriter.println("HTTP/1.1 200 OK");
        printWriter.println("Content-Type:text/html;charset=utf-8");
        printWriter.println("Content-Length:" + body.getBytes().length);
        printWriter.println();
        printWriter.write(body);
        printWriter.close();
        socket.close();
    }
}
